//
// Created by heqian on 17-8-2.
//

#include "Image.h"
#include "../utils/Prt.h"

namespace img {

    uint32_t Image::getWidth() const {
        return mWidth;
    }

    void Image::setWidth(uint32_t mWidth) {
        Image::mWidth = mWidth;
        setFormat(mFormat);
    }

    uint32_t Image::getHeight() const {
        return mHeight;
    }

    void Image::setHeight(uint32_t mHeight) {
        Image::mHeight = mHeight;
    }

    uint32_t Image::getStride() const {
        return mStride;
    }

    void Image::setStride(uint32_t mStride) {
        Image::mStride = mStride;
    }

    uint32_t Image::getFlags() const {
        return mFlags;
    }

    void Image::setFlags(uint32_t mFlags) {
        Image::mFlags = mFlags;
    }

    void *Image::getData() const {
        return mpData;
    }

    void Image::setpData(void *mpData) {
        Image::mpData = mpData;
    }

    ImageFormat Image::getFormat() const {
        return mFormat;
    }

    void Image::setFormat(ImageFormat format) {
        Image::mFormat = format;
        switch (format) {
            case IMAGE_FORMAT_RGBA_8888:
                mStride *= 4;
                break;

            case IMAGE_FORMAT_RGB_565:
                mStride *= 2;
                break;

            case IMAGE_FORMAT_RGBA_4444:
                mStride *= 2;
                break;

            case IMAGE_FORMAT_A_8:
                break;

            default:
                return;
        }
    }

    Image::Image() :
            mWidth(0),
            mHeight(0),
            mStride(0),
            mFormat(IMAGE_FORMAT_NONE),
            mFlags(0),
            mpData(nullptr),
            mFreeData(false) {
    }

    Image::Image(uint32_t width, uint32_t height, void *pData, ImageFormat format) :
            mFlags(0) {
        create(width, height, format);
        memcpy(mpData, pData, mStride * height);
    }

    Image::~Image() {
        if (mFreeData && !mpData) {
            free(mpData);
            mpData = nullptr;
            mFreeData = false;
        }
    }

    Image::Image(uint32_t width, uint32_t height, ImageFormat format) :
            mFlags(0) {
        create(width, height, format);
    }

    void Image::create(uint32_t width, uint32_t height, ImageFormat format) {
        mWidth = width;
        mHeight = height;
        mFormat = format;
        mStride = width;
        setFormat(format);
        mFreeData = true;
        mpData = malloc(mStride * height);
        memset(mpData, 0, mStride * height);
    }

}
